package lxs.swift.tool.http;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lxs.swift.tool.IOStreamer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public class Receiver {
    private final Sender sender;
    private final InputStream inputStream;

    private final int statusCode;

    public Receiver(Sender sender) {
        this.sender = sender;
        try {
            this.statusCode = sender.connection.getResponseCode();
            if (sender.connection.getDoInput()) {
                InputStream errorStream = sender.connection.getErrorStream();
                InputStream inputStream;
                try {
                    inputStream = sender.connection.getInputStream();
                } catch (Exception e) {
                    inputStream = null;
                }
                this.inputStream = errorStream == null ? inputStream : errorStream;
            } else {
                this.inputStream = null;
            }
        } catch (IOException e) {
            sender.close();
            throw new RuntimeException(e);
        }
    }

    public int statusCode() {
        return statusCode;
    }

    public String content() {
        return new String(bytes(), sender.config.charset);
    }

    public byte[] bytes() {
        if (inputStream == null) {
            return new byte[]{};
        }
        byte[] bytes = IOStreamer.toBytes(inputStream);
        sender.close();
        return bytes;
    }

    public JSONObject jsonObject() {
        if (inputStream == null) return null;
        JSONObject objects = JSON.parseObject(inputStream, sender.config.charset);
        sender.close();
        return objects;
    }

    public JSONArray jsonArray() {
        if (inputStream == null) return null;
        JSONArray array = JSON.parseArray(inputStream);
        sender.close();
        return array;
    }


    public void transferTo(Path path) {
        if (inputStream == null) return;
        try {
            byte[] bytes = bytes();
            Files.write(path, bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void transferTo(File file) {
        try {
            Files.write(file.toPath(), bytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void transferTo(OutputStream outputStream) {
        if (inputStream == null) return;
        IOStreamer streamer = IOStreamer.of(inputStream, outputStream);
        streamer.transfer();
        streamer.close();
        sender.close();
    }
}
